package com.spx.chapter05.source;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;

import java.util.Random;

/**
 * create by undeRdoG on  2022-04-29  16:49
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class CustomParallelSourceFunction {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Integer> integerDataStreamSource = env.addSource(new MyParallelSourceFunction()).setParallelism(2);

        integerDataStreamSource.print("integerDataStreamSource");

        env.execute();
    }


    /**
     * 实现自定义的 并行 source
     */
    public static class MyParallelSourceFunction implements ParallelSourceFunction<Integer> {

        private Boolean isActive = true;

        private Random random = new Random();

        private int count = 10;

        private int start = 0;

        @Override
        public void run(SourceContext<Integer> sourceContext) throws Exception {
            while (this.isActive) {
                sourceContext.collect(this.random.nextInt());
                this.start++;
                if (this.start == count) {
                    cancel();
                }
            }
        }

        @Override
        public void cancel() {
            this.isActive = false;
        }
    }

}
